#include "UnBoundedMailBox.h"

UnBoundedMailBox::UnBoundedMailBox():
	m_maxLength(0)
{
mutex=new Mutex();
m_Nonempty=new Semaphore(0);
}

UnBoundedMailBox::~UnBoundedMailBox()
{
delete mutex;
delete m_Nonempty;
}

bool UnBoundedMailBox::isEmpty()
{
	return mailbox.empty();
}

int UnBoundedMailBox::PutIn(Message* m)
{
//	m_empty.down();
	mutex->lock(self());
	//if (m->type()==1)
	//printf("Pushing...Message  from %d to %d\n",m->from(),m->to());
	mailbox.push(m);
	if (mailbox.size()> m_maxLength)
		m_maxLength=mailbox.size();
	m_Nonempty->up();
	mutex->unlock();
	return 0;
}

Message* UnBoundedMailBox::Extract()
{
	m_Nonempty->down();
	mutex->lock(self());
	Message* msg=mailbox.front();
	//if (msg->type()==1)
	//printf("Extracting...%s from %d to %d\n",msg->text(),msg->from(),msg->to());
	mailbox.pop();
	mutex->unlock();
//	m_empty.up();
	return msg;
}

int UnBoundedMailBox::getMaxSize()
{
	return m_maxLength;
}

int UnBoundedMailBox::getSize()
{
	return mailbox.size();
}

void UnBoundedMailBox::cleanMailBox()
{
	while (!mailbox.empty())
	{
		mailbox.pop();
	}
	m_maxLength=0;
	
	if(m_Nonempty->getValue()>0) m_Nonempty->setValue(0);
}







